using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace LZX.Installer
{
    public class InstallerWindow:EditorWindow
    {
        public VisualTreeAsset uxml;
        public StyleSheet uss;
        [MenuItem("Tools/LZX/Installer")]
        public static void ShowWindow()
        {
            EditorWindow.GetWindow<InstallerWindow>();
        }
        private void CreateGUI()
        {
            var root = uxml.CloneTree();
            root.styleSheets.Add(uss);
            var label_hybridclrversion = root.Q<Label>("label_hybridclrversion");
            label_hybridclrversion.text = "本地版本：";
            label_hybridclrversion.text += InstallerController.HyBridCLRHasInstalled() ? InstallerController.GetHyBridCLRLoaclVersion() : "Not Installed";
            
            
            var label_hybridclrInstalledversion = root.Q<Label>("label_hybridclrInstalledversion");
            label_hybridclrInstalledversion.text = "包版本：";
            string hyversion = "";
            label_hybridclrInstalledversion.text += GetPackageInstallerWithmainfest("com.code-philosophy.hybridclr",out hyversion) ? hyversion : "Not Installed";
            
            
            var label_lzxhotupdateversion = root.Q<Label>("label_lzxhotupdateversion");
            string lzxversion = "";
            label_lzxhotupdateversion.text = GetPackageInstallerWithmainfest("lzx.hotupdate.main",out lzxversion)? lzxversion : "Not Installed";
            var label_lzxhotupdateinit = root.Q<Label>("label_lzxhotupdateinit");
            label_lzxhotupdateinit.text += InstallerController.LZXHasInited() ? "TRUE" : "FALSE";
            
            
            string searchPath = Path.Combine(Application.dataPath, "Plugins/UniTask/package.json");
            bool unitask = false;
            string universion = "Non Installed";
            if (File.Exists(searchPath))
            {
                string json = File.ReadAllText(searchPath);
                var jsonObj = JObject.Parse(json);
                universion = jsonObj["version"]?.ToString();
                unitask = true;
            }
            var label_unitaskversion = root.Q<Label>("label_unitaskversion");
            if (!unitask)
                 GetPackageInstallerWithmainfest("com.cysharp.unitask", out universion);
            label_unitaskversion.text = universion;

            var label_lzxresourceversion = root.Q<Label>("label_lzxresourceversion");
            string lzxresourceversion = "";
            bool resourceHasInstall = GetPackageInstallerWithmainfest("lzx.hotupdate.resource", out lzxresourceversion);
            label_lzxresourceversion.text = resourceHasInstall ? lzxresourceversion : "Not Installed";
            var btn_resource = root.Q<Button>("btn_installresource");
            btn_resource.text = resourceHasInstall ? "Remove" : "Install";
            btn_resource.clicked += resourceHasInstall ? 
                () =>
                {
                    string symbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
                    // 分离成数组
                    string[] symbolArray = symbols.Split(';');
                    string symbolToRemove = "LZXResource";
                    // 删除指定宏定义
                    string updatedSymbols = string.Join(";", symbolArray.Where(symbol => symbol != symbolToRemove));
                    // 设置更新后的宏定义
                    PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, updatedSymbols);
                    Debug.Log($"Removed scripting define symbol: {symbolToRemove}");
                    InstallerController.RemovePackage("lzx.hotupdate.resource");
                }
                :
                () =>
                {
                    InstallerController.InstallPackage("https://gitee.com/xuan020813/lzxhotupdate.git?path=Resource",
                        "lzx.hotupdate.resource");
                    // 获取当前的构建目标组
                    BuildTargetGroup targetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;

                    // 获取现有的宏定义
                    string currentDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
                    string defineSymbol = "LZXResource";
                    // 检查是否已经存在
                    if (!currentDefines.Contains(defineSymbol))
                    {
                        // 如果不存在，添加新的宏定义
                        currentDefines = string.IsNullOrEmpty(currentDefines) ? defineSymbol : $"{currentDefines};{defineSymbol}";
                        PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, currentDefines);
                        UnityEngine.Debug.Log($"宏定义 {defineSymbol} 已添加到 {targetGroup}");
                    }
                    else
                    {
                        UnityEngine.Debug.Log($"宏定义 {defineSymbol} 已存在于 {targetGroup}");
                    }
                };
            
            var label_lzxdemoversion = root.Q<Label>("label_lzxDemoversion");
            string lzxdemoversion = "";
            bool demoHasInstall = GetPackageInstallerWithmainfest("lzx.hotupdate.demo", out lzxdemoversion);
            label_lzxdemoversion.text = demoHasInstall ? lzxdemoversion : "Not Installed";
            var btn_demo = root.Q<Button>("btn_installDemo");
            btn_demo.text = demoHasInstall ? "Remove" : "Install";
            btn_demo.clicked += demoHasInstall ? 
                () => InstallerController.RemovePackage("lzx.hotupdate.demo") :
                () => InstallerController.InstallPackage("https://gitee.com/xuan020813/lzxhotupdate.git?path=Demo","lzx.hotupdate.demo");
            
            root.Q<Button>("btn_installer").clicked += Installer;
            rootVisualElement.Add(root);
        }
        private static void Installer()
        {
            InstallerController.InstallPackages();
            AssetDatabase.Refresh();
            UnityEditor.Compilation.CompilationPipeline.RequestScriptCompilation();
        }
        public static bool GetPackageInstallerWithmainfest(string packageName,out string version)
        {
            string manifestPath = Path.Combine(Application.dataPath, "../Packages/manifest.json");
            string manifestContent = File.ReadAllText(manifestPath);
            string searchString = $"\"{packageName}\": \"";
            int startIndex = manifestContent.IndexOf(searchString);
            if (startIndex != -1)
            {
                version = GetPackageVersion(packageName);
                return true;
            }
            version = "";
            return false;
        }
        private static string GetPackageVersion(string packageName)
        {
            string packageJson =
                Application.dataPath.Replace("Assets", $"/Packages/{packageName}/package.json");
            JObject json = JObject.Parse(File.ReadAllText(packageJson));
            return json["version"].ToString();
        }
    }
}

